#include "ExperimentThread.h"

//全局变量
extern QMap<int,QVariantMap> expLogInfo;
extern QString currentStep;//步骤
extern QMap<int,QVariantMap> expSendList;
extern int expStatus;//实验状态 0空闲 1实验中 2暂停
extern int expStep;
QDateTime stepStartTime;
extern bool isProductTesting;//产物检测
extern QString dataThresholdType;
extern double dataThreshold;
extern int  productSyringStep;//产物注射器步骤
extern QDateTime productSyringStartTime;

ExperimentThread::ExperimentThread()
{

}


ExperimentThread& ExperimentThread::I(){
    static ExperimentThread instance;
    return instance;
}


void ExperimentThread::run()
{
    UdpClient *udpClient;
    udpClient=UdpClient::getInstance();

    if(expSendList.lastKey()<expStep){
        QVariantMap map= expSendList[expStep-1];
        expLogInfo[map["Step"].toInt()]["Status"]="完成";
        expLogInfo[map["Step"].toInt()]["FinishTime"]=commonClient->GetDateTimeStr();

        qint64 msecs = QDateTime::currentDateTime().toMSecsSinceEpoch() - stepStartTime.toMSecsSinceEpoch();
        expLogInfo[map["Step"].toInt()]["Time"]=QString::number(msecs);

        udpClient->ClientSendingData(commonClient->GetSendData(CommCommand::I().stopExperiment()));
    }

    // map["Type"]="0";//0 正常执行(Info发送指令) 1循环(开始循环,结束循环) 2 跳过("") 3等待(等待时长)
    QVariantMap map= expSendList[expStep];

    qint64 msecs = QDateTime::currentDateTime().toMSecsSinceEpoch() - stepStartTime.toMSecsSinceEpoch();

    if(map["Type"]=="0"){
        if(map["Info"].toString().split(" ").length()>8){
            staticUseNum(map["Info"].toString().split(" ")[7]);
        }
        udpClient->ClientSendingData(commonClient->GetSendData(map["Info"].toString()));
        expLogInfo[map["Step"].toInt()]["Status"]="进行中";
        logClient->WriteLog("CommLog","发送:\n"+map["Info"].toString());
        stepStartTime=QDateTime::currentDateTime();
        if(expStep>1){
            QVariantMap finishMap=expSendList[expStep-1];
            expLogInfo[finishMap["Step"].toInt()]["Status"]="完成";
            expLogInfo[finishMap["Step"].toInt()]["FinishTime"]=commonClient->GetDateTimeStr();
            expLogInfo[finishMap["Step"].toInt()]["Time"]=QString::number(msecs);
        }
        currentStep=map["Step"].toString();
        QMLSignal::I().emitRefExperimentLog();     // 发信号通知前端
    }
    else if(map["Type"]=="1")
    {
        if(expStep==expSendList.lastKey()){
            QVariantMap map= expSendList[expStep];
            expLogInfo[map["Step"].toInt()]["Status"]="完成";
            expLogInfo[map["Step"].toInt()]["FinishTime"]=commonClient->GetDateTimeStr();

            qint64 msecs = QDateTime::currentDateTime().toMSecsSinceEpoch() - stepStartTime.toMSecsSinceEpoch();
            expLogInfo[map["Step"].toInt()]["Time"]=QString::number(msecs);

            udpClient->ClientSendingData(commonClient->GetSendData(CommCommand::I().stopExperiment()));
            return;
        }
        else{
            QVariantMap nextMap= expSendList[expStep+1];

            if(nextMap["Type"]=="0")
            {
                if(nextMap["Info"].toString().split(" ").length()>8){
                    staticUseNum(nextMap["Info"].toString().split(" ")[7]);
                }
                udpClient->ClientSendingData(commonClient->GetSendData(nextMap["Info"].toString()));
                expLogInfo[map["Step"].toInt()]["Status"]=map["Info"];
                expLogInfo[nextMap["Step"].toInt()]["Status"]="进行中";
                stepStartTime=QDateTime::currentDateTime();

                if(expStep>1){
                    QVariantMap finishMap=expSendList[expStep-1];
                    expLogInfo[finishMap["Step"].toInt()]["Status"]="完成";
                    expLogInfo[finishMap["Step"].toInt()]["FinishTime"]=commonClient->GetDateTimeStr();
                    expLogInfo[finishMap["Step"].toInt()]["Time"]=QString::number(msecs);
                }
                QMLSignal::I().emitRefExperimentLog();     // 发信号通知前端
            }
            else
            {
                expStep++;
                run();
            }
        }

    }
    else if(map["Type"]=="2")
    {
        expLogInfo[map["Step"].toInt()]["Status"]="跳过";
        stepStartTime=QDateTime::currentDateTime();

        if(expStep>1){
            expLogInfo[map["Step"].toInt()-1]["Status"]="完成";
            expLogInfo[map["Step"].toInt()-1]["FinishTime"]=commonClient->GetDateTimeStr();
            expLogInfo[map["Step"].toInt()-1]["Time"]=QString::number(msecs);
            QMLSignal::I().emitRefExperimentLog();     // 发信号通知前端
        }

        if(map["Step"].toInt()==expSendList.lastKey()){
            udpClient->ClientSendingData(commonClient->GetSendData(CommCommand::I().stopExperiment()));
        }
        else
        {
            expStep++;
            run();
        }
    }
    else if(map["Type"]=="3"){
        expLogInfo[map["Step"].toInt()]["Status"]="进行中";
        if(expStep>1){
            QVariantMap finishMap=expSendList[expStep-1];
            expLogInfo[finishMap["Step"].toInt()]["Status"]="完成";
            expLogInfo[finishMap["Step"].toInt()]["FinishTime"]=commonClient->GetDateTimeStr();
            expLogInfo[finishMap["Step"].toInt()]["Time"]=QString::number(msecs);

        }
        stepStartTime=QDateTime::currentDateTime();

        QMLSignal::I().emitRefExperimentLog();     // 发信号通知前端
        QTimer::singleShot(map["Info"].toInt()*1000, [this]() {  // 使用 QTimer 的单次定时器，延时 3 秒
            if(expStatus==1){
                UdpClient *udpClient;
                udpClient=UdpClient::getInstance();
                QVariantMap map= expSendList[expStep];

                qint64 newMsecs = QDateTime::currentDateTime().toMSecsSinceEpoch() - stepStartTime.toMSecsSinceEpoch();
                expLogInfo[map["Step"].toInt()]["Status"]="完成";
                expLogInfo[map["Step"].toInt()]["FinishTime"]=commonClient->GetDateTimeStr();
                expLogInfo[map["Step"].toInt()]["Time"]=QString::number(newMsecs);

                if(expStep+1>expSendList.lastKey()){
                    QVariantMap map= expSendList[expStep-1];
                    expLogInfo[map["Step"].toInt()]["Status"]="完成";
                    expLogInfo[map["Step"].toInt()]["FinishTime"]=commonClient->GetDateTimeStr();

                    qint64 msecs = QDateTime::currentDateTime().toMSecsSinceEpoch() - stepStartTime.toMSecsSinceEpoch();
                    expLogInfo[map["Step"].toInt()]["Time"]=QString::number(msecs);

                    udpClient->ClientSendingData(commonClient->GetSendData(CommCommand::I().stopExperiment()));
                    return;
                }else{
                    QVariantMap nextMap= expSendList[expStep+1];

                    if(nextMap["Info"].toString().split(" ").length()>8){
                        staticUseNum(nextMap["Info"].toString().split(" ")[7]);
                    }
                    udpClient->ClientSendingData(commonClient->GetSendData(nextMap["Info"].toString()));
                    expLogInfo[nextMap["Step"].toInt()]["Status"]="进行中";
                    currentStep=nextMap["Step"].toString();
                    stepStartTime=QDateTime::currentDateTime();
                }

                QMLSignal::I().emitRefExperimentLog();
            }
        });
    }
    else if(map["Type"]=="4")
    {
        stepStartTime=QDateTime::currentDateTime();

        QVariantMap lastMap= expSendList[expStep-1];
        if(lastMap["Type"]!=7){
            expLogInfo[lastMap["Step"].toInt()]["Status"]="完成";
            expLogInfo[lastMap["Step"].toInt()]["FinishTime"]=commonClient->GetDateTimeStr();
            expLogInfo[lastMap["Step"].toInt()]["Time"]=QString::number(msecs);
        }
        expLogInfo[map["Step"].toInt()]["Status"]="检测中";
        QString info=map["Info"].toString();
        QStringList list=info.split(",");
        dataThreshold=list[1].toDouble();
        dataThresholdType=list[0];

        isProductTesting=true;
        expStep++;
        QMLSignal::I().emitRefExperimentLog();     // 发信号通知前端
    }
    else if(map["Type"]=="7")//同步注射器
    {
        productSyringStartTime=QDateTime::currentDateTime();

        expLogInfo[map["Step"].toInt()]["Status"]="进行中";
        if(expStep>1){
            QVariantMap finishMap=expLogInfo[expStep-1];
            expLogInfo[finishMap["Step"].toInt()]["Status"]="完成";
            expLogInfo[finishMap["Step"].toInt()]["FinishTime"]=commonClient->GetDateTimeStr();
            expLogInfo[finishMap["Step"].toInt()]["Time"]=QString::number(msecs);
        }

        udpClient->ClientSendingData(commonClient->GetSendData(map["Info"].toString()));

        QMLSignal::I().emitRefExperimentLog();     // 发信号通知前端
        productSyringStep=expStep;
        expStep++;
        run();
    }
}

void ExperimentThread::staticUseNum(QString type)//01注射器 02阀门 03转盘
{
    if(type=="01")//注射器
    {
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        QDateTime current=QDateTime::currentDateTime();
        QString dateStr=current.toString("yyyy-MM-dd");

        QString sql=QString("Update DataStatistics Set Syringe=Syringe+1 Where StaticDate='%1'").arg(dateStr);
        query.exec(sql);
    }
    else if(type=="02" ||type=="03")
    {
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        QDateTime current=QDateTime::currentDateTime();
        QString dateStr=current.toString("yyyy-MM-dd");

        QString sql=QString("Update DataStatistics Set AirBottle=AirBottle+1 Where StaticDate='%1'").arg(dateStr);
        query.exec(sql);
    }
    if(type=="03")
    {
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        QDateTime current=QDateTime::currentDateTime();
        QString dateStr=current.toString("yyyy-MM-dd");

        QString sql=QString("Update DataStatistics Set Turntable=Turntable+1 Where StaticDate='%1'").arg(dateStr);
        query.exec(sql);
    }
}
